package com.dingreading.cloud.admin.controller;

import com.dingreading.cloud.admin.dto.SubjectLessonIssueDto;
import com.dingreading.cloud.admin.entity.SubjectLessonIssueImg;
import com.dingreading.cloud.admin.service.SubjectLessonIssueImgService;
import com.dingreading.cloud.admin.service.SubjectLessonIssueService;
import com.dingreading.cloud.admin.util.redis.RedisService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.common.util.qyweixin.AccessTokenDto;
import com.dingreading.cloud.common.util.qyweixin.QyWeiXinUtil;
import com.dingreading.cloud.common.util.qyweixin.QyWeixinMsg;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/subjectLessonIssue")
@Api(tags = "总部-活动课次建议管理")
public class SubjectLessonIssueController {

    @Value("${qyweixin.corpid}")
    private String corpid;
    @Value("${qyweixin.secret}")
    private String secret;
    @Value("${qyweixin.lessonchatid}")
    private String lessonchatid;

    @Resource
    private SubjectLessonIssueService subjectLessonIssueService;
    @Resource
    private SubjectLessonIssueImgService subjectLessonIssueImgService;
    @Resource
    private RedisService redisService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "层级名/课次名/门店名/发起人姓名/处理人姓名") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "开始时间 yyyy-MM-dd") @RequestParam(value = "beginDate", required = false) String beginDate,
            @ApiParam(value = "结束时间 yyyy-MM-dd") @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(value = "状态 0.取消 1.未处理 2.已处理") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "建议uid") @RequestParam(value = "uid", required = false) String uid
    ) {
        Page<SubjectLessonIssueDto> page = subjectLessonIssueService.pageList(
                pageUtil, null, null, keyword, beginDate, endDate, status, uid
        );

        List<SubjectLessonIssueDto> list = page.getRecords();

        if (CollectionUtils.isNotEmpty(list)) {
            // 获取图片集合
            List<String> uids = list.stream().map(SubjectLessonIssueDto::getUid).collect(Collectors.toList());
            List<SubjectLessonIssueImg> imgList = subjectLessonIssueImgService.getImgList(uids);
            if (CollectionUtils.isNotEmpty(imgList)) {
                Map<String, List<SubjectLessonIssueImg>> map = imgList.stream()
                        .collect(Collectors.groupingBy(SubjectLessonIssueImg::getIssueUid, LinkedHashMap::new, Collectors.toList()));
                if (!map.isEmpty()) {
                    for (SubjectLessonIssueDto issue : list) {
                        issue.setImgList(map.get(issue.getUid()));
                    }
                }
            }
        }

        PageBeanDto dto = new PageBeanDto();
        dto.setTotal(page.getTotalRow());
        dto.setList(list);

        return R.ok(dto);
    }


    @ApiOperation(value = "获取")
    @PostMapping(value = "/getBean")
    public R<Object> getBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "意见uid") @RequestParam(value = "uid") String uid
    ) {
        SubjectLessonIssueDto data = subjectLessonIssueService.getDtoByUid(uid);
        if (data == null)
            return R.fail("获取失败");

        List<SubjectLessonIssueImg> imgList = subjectLessonIssueImgService.getImgList(uid);
        data.setImgList(imgList);

        return R.ok(data);
    }


    @ApiOperation(value = "处理意见")
    @PostMapping(value = "/replyIssue")
    public R<Object> replyIssue(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "意见uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "处理内容") @RequestParam(value = "replyContent", required = false) String replyContent
    ) {
        SubjectLessonIssueDto data = subjectLessonIssueService.getDtoByUid(uid);
        if (data == null)
            return R.fail("意见获取失败");
        if (data.getStatus().equals(0))
            return R.fail("意见已被取消，不能操作");
        if (data.getStatus().equals(2)) {
            // 已处理判断日期
            if (TimeUtil.moreThanDay(data.getReplyTime(), 7))
                return R.fail("已处理超过7天，不能操作");
        }

        boolean l = subjectLessonIssueService.updateReply(uid, replyContent, headStaffUid, headStaffName);
        if (!l)
            return R.fail("处理失败");

        // 企业微信获取access_token
        String accessToken = getQiWeiAccessToken();
        String time = DateUtil.getNowDatetimeStr();
        String staffName = StringUtils.isNotBlank(data.getMob()) ? data.getAddStaffName() + " / " + data.getMob() : data.getAddStaffName();
        QyWeiXinUtil.sendToChat(accessToken, lessonchatid,
                QyWeixinMsg.lessonIssueReply(data.getStoreName(), staffName, data.getLevelName(), data.getLessonName(), data.getIssueContent(), headStaffName, replyContent, time));

        return R.ok();
    }

    /**
     * 企业微信获取access_token
     */
    private String getQiWeiAccessToken() {
        String accessToken = (String) redisService.get(RedisParam.QYWEINXIN_ACCESS_TOKEN);
        if (com.alibaba.excel.util.StringUtils.isBlank(accessToken)) {
            AccessTokenDto dto = QyWeiXinUtil.getAccessToken(corpid, secret);
            if (dto != null) {
                accessToken = dto.getAccess_token();
                int expires_in = dto.getExpires_in();
                // redis缓存accessToken
                redisService.set(RedisParam.QYWEINXIN_ACCESS_TOKEN, accessToken, expires_in);
            }
        }
        return accessToken;
    }

}
